package com.detech.sboh.base.config.hibernate;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

@Configuration
public class HibernateConfig {

    public String current_session_context_class = "org.springframework.orm.hibernate5.SpringSessionContext";

    @Resource
    private DataSource dataSource;

    @Bean
    public LocalSessionFactoryBean sessionFactoryBean() throws SQLException {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setPackagesToScan("com.detech.sboh.base.hibernate.*");// dao和entity的扫描包路径，可写多个路径参数

        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        properties.setProperty("hibernate.hbm2ddl.auto", "none");
        properties.setProperty("hibernate.show_sql", "false");
        properties.setProperty("hibernate.format_sql", "false");
        properties.setProperty("hibernate.current_session_context_class", current_session_context_class);
        sessionFactoryBean.setHibernateProperties(properties);

        return sessionFactoryBean;
    }

    @Bean
    public HibernateTransactionManager transactionManager() throws SQLException {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setDataSource(dataSource);
        transactionManager.setSessionFactory(sessionFactoryBean().getObject()); // 注入sessionFactory
        return transactionManager;
    }

    @Bean
    public TransactionInterceptor transactionInterceptors() throws SQLException {
        TransactionInterceptor transInterceptor = new TransactionInterceptor();
        transInterceptor.setTransactionManager(transactionManager());
        Properties props = new Properties();
        props.setProperty("*", "PROPAGATION_REQUIRED");
        transInterceptor.setTransactionAttributes(props);
        return transInterceptor;
    }

    @Bean
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        beanNameAutoProxyCreator.setProxyTargetClass(true);
        beanNameAutoProxyCreator.setBeanNames("*ServiceImpl");
        beanNameAutoProxyCreator.setInterceptorNames("transactionInterceptors");
        return beanNameAutoProxyCreator;
    }

}